#轻量写作 By 于小丘
#coding:utf-8
#感谢开发下面这些库的大佬们！
from logging import root
from msilib.schema import Control, Font, RemoveFile
from re import S
import time
import tkinter
import tkinter.filedialog
import tkinter.messagebox
from tkinter.tix import PopupMenu
from tkinter.ttk import Sizegrip
import pygame
import os
from xml.dom.pulldom import END_DOCUMENT
pygame.init()

def NewFileMenu():
    NewFile(0)

def OpenFileMenu():
    OpenFile(0)

def SaveFileMenu():
    SaveFile(0)

def SavePlusFileMenu():
    SavePlusFile(0)

def NewFile(NFEvent):
    NewFileTips=tkinter.messagebox.askyesno('提示','当前未保存的文件将会被清空!\n是否继续?')
    if NewFileTips:
        Editor.delete('1.0','end')
        MainWindow.title("新文件.txt - 轻量写作")

def OpenFile(OFEvent):
    RemoveFileTips = tkinter.messagebox.askyesno('提示','当前未保存的文件将会被清空!\n是否继续?')
    if RemoveFileTips:
        r = tkinter.filedialog.askopenfilename(title = "打开文件将会在末尾展示文件,仅支持UTF8",filetypes=[("文本文件.",'*.txt')])
        r = r.split("/")
        rlen = int(len(r))
        rlenxh = 2
        saveurl = r[0] + "\\" + r[1]
        while rlenxh < rlen:
            saveurl = saveurl + "\\" + r[rlenxh]
            rlenxh = rlenxh + 1
        Doculocat = saveurl
        AppConfig = open("locatsave.ini","w")
        AppConfig.writelines(Doculocat)
        AppConfig.close()
        Docu = open(saveurl,"r",encoding='UTF-8')
        DocuName = Docu.name
        OpenMode = Docu.mode
        DocuFid = str(Docu.fileno)
        Docu = Docu.read()
        Editor.delete(1.0,tkinter.END)
        Editor.insert("end",Docu)
        TitlePage = DocuName + " - " + "轻量写作"
        MainWindow.title(TitlePage)
        PageInfo = 0
        PageInfoes = "打开方式：" + OpenMode + "     描述符：" + DocuFid
        PageInfo = tkinter.Label(MainWindow,text=PageInfoes)
        PageInfo.pack()

def SaveFile(SFEvent):
    try:
        AppConfig = open("locatsave.ini","r")
        saveurl = AppConfig.read()
    except:
        w = tkinter.filedialog.asksaveasfilename(title="保存文件",initialdir=r"Desktop",initialfile="我的文件.txt",filetypes=[("文本文件","*.txt")])
        w = w.split("/")
        wlen = int(len(w))
        wlenxh = 2
        saveurl = w[0] + "\\" + w[1]
        while wlenxh < wlen:
            saveurl = saveurl + "\\" + w[wlenxh]
            wlenxh = wlenxh + 1
    Docu = open(saveurl,"w",encoding='UTF-8')
    DocuName = Docu.name
    Pagers = Editor.get("1.0",'end-1c')
    Docu.writelines(Pagers)
    localtime = time.asctime( time.localtime(time.time()))
    TitlePage = DocuName + " 保存成功 " + localtime + " - 轻量写作"
    MainWindow.title(TitlePage)
    Docu.close()

def SavePlusFile(SPFEvent):
    w = tkinter.filedialog.asksaveasfilename(title="保存文件",initialdir=r"Desktop",initialfile="我的文件.txt",filetypes=[("文本文件","*.txt")])
    w = w.split("/")
    wlen = int(len(w))
    wlenxh = 2
    saveurl = w[0] + "\\" + w[1]
    while wlenxh < wlen:
        saveurl = saveurl + "\\" + w[wlenxh]
        wlenxh = wlenxh + 1
    Docu = open(saveurl,"w",encoding='UTF-8')
    DocuName = Docu.name
    Pagers = Editor.get("1.0",'end-1c')
    Docu.writelines(Pagers)
    localtime = time.asctime( time.localtime(time.time()))
    TitlePage = DocuName + " 保存成功 " + localtime + " - 轻量写作"
    MainWindow.title(TitlePage)
    Docu.close()

def Popup_Menu(OnClickRightKeyevent):
    popup.post(OnClickRightKeyevent.x_root,OnClickRightKeyevent.y_root)

def Findor():
    FindAsk = tkinter.Toplevel(MainWindow,width=230,height=50)
    a,b=230,50
    c=MainWindow.winfo_x()+((MainWindow.winfo_width()-a)/2)
    d=MainWindow.winfo_y()+((MainWindow.winfo_height()-b)/2)
    FindAsk.geometry('%dx%d+%d+%d' % (a,b,c,d)) # 查找窗口居中
    FindAsk.attributes("-toolwindow", 1) # 无最大化，最小化
    FindAsk.transient(MainWindow) # 窗口只置顶root之上
    FindAsk.resizable(False,False) # 不可调节窗体大小
    FindAsk.focus_force()  # 得到焦点
    en1=tkinter.Entry(FindAsk)  # 输入查找关键字的单行文本框
    en1.pack(side=tkinter.LEFT,padx=10)    
    but1=tkinter.Button(FindAsk,text=" 确定",command=findok(en1.get()))
    but1.pack(side=tkinter.LEFT,padx=(0,10))
    en1.focus_force() # 单行文本框得到焦点

def findok(key): # 查找关键词函数
    start='1.0' # 初始化，查找起始位置
    if key=='': # 关键词为空，退出
        return
    while True: # 循环查找
        weizi=MainWindow.search(key,start,tkinter.END)
        print(weizi) # 输出查找返回的结果
        if weizi=='' : # 返回值为空，就是找不到
            break # 跳出循环
        MainWindow.tag_add('tag1',weizi, weizi+'+' + str(len(key))+'chars') # 找到了就新建一个标签
        start=weizi+'+' + str(len(key))+'chars' # 找到了，就把起始位置定义为：找到位置+关键字的长度

def CloseAPP():
    CloseChoose=tkinter.messagebox.askyesno('提示','当前未保存的文件将会被清空!\n是否继续?')
    if CloseChoose:
        exit()

MainWindow = tkinter.Tk()
MainWindow.tk.call("source","azure.tcl")
MainWindow.tk.call("set_theme","light")
MainWindow.geometry("800x420")
MainWindow.title("新文件.txt - 轻量写作")
menu = tkinter.Menu(MainWindow)
submenu = tkinter.Menu(menu,tearoff=0)
submenu.add_command(label="新建文件",command=NewFileMenu,accelerator="Ctrl+N")
submenu.add_command(label="打开文件",command=OpenFileMenu,accelerator="Ctrl+O")
submenu.add_separator()
submenu.add_command(label="保存文件",command=SaveFileMenu,accelerator="Ctrl+S")
submenu.add_command(label="另存为……",command=SavePlusFileMenu,accelerator="Ctrl+Shift+S")
submenu.add_separator()
submenu.add_command(label="强制关闭(不保存文件)",command=CloseAPP,accelerator="Alt+F4")
menu.add_cascade(label="文件(F)",menu=submenu)
submenu = tkinter.Menu(menu,tearoff=0)
submenu.add_command(label="撤销",accelerator="Ctrl+Z")
submenu.add_command(label="重做",accelerator="Ctrl+Y")
submenu.add_separator()
submenu.add_command(label="剪切",accelerator="Ctrl+X")
submenu.add_command(label="复制",accelerator="Ctrl+C")
submenu.add_command(label="粘贴",accelerator="Ctrl+V")
submenu.add_separator()
submenu.add_command(label="首选项")
menu.add_cascade(label="编辑(E)",menu=submenu,underline=3)
submenu = tkinter.Menu(menu,tearoff=0)
submenu.add_command(label="查找",accelerator="Ctrl+F",command=Findor)
submenu.add_separator()
submenu.add_command(label="切换编辑器背景色")
submenu.add_command(label="切换编辑器前景色")
submenu.add_command(label="切换")
menu.add_cascade(label="查看(V)",menu=submenu,underline=3)
MainWindow.config(menu=menu)
submenu = tkinter.Menu(menu,tearoff=0)
submenu.add_command(label="关于")
menu.add_cascade(label="帮助(H)",menu=submenu,underline=3)
MainWindow.config(menu=menu)
Editor = tkinter.Text(MainWindow,selectforeground="gray",width=100,font="MiSans-Regular.ttf")
scroll = tkinter.Scrollbar()
scroll.pack(side=tkinter.RIGHT,fill=tkinter.Y)
scroll.config(command=Editor.yview)
Editor.config(yscrollcommand=scroll.set)
Editor.pack()

popup = tkinter.Menu(MainWindow,tearoff=0)
popup.add_command(label="剪切",accelerator="Ctrl+Z")
popup.add_command(label="复制",accelerator="Ctrl+C")
popup.add_command(label="粘贴",accelerator="Ctrl+V")

MainWindow.bind("<Button-3>",Popup_Menu)

MainWindow.bind("<Control-s>",SaveFile)
MainWindow.bind("<Control-o>",OpenFile)
MainWindow.bind("<Control-n>",NewFile)
MainWindow.bind("<Control-Shift-s>",SavePlusFile)

MainWindow.protocol("WM_DELETE_WINDOW",CloseAPP)
si = Sizegrip()
si.pack(side=tkinter.BOTTOM,anchor="se")
try:
    FileLocationOpen = open("locatsave.ini","r")
    FileLocation = FileLocationOpen.read()
    OpenLastFileTipsPage = "是否打开上次打开的文件继续编辑?\n" + FileLocation
    OpenLastFileTips = tkinter.messagebox.askyesno('提示',OpenLastFileTipsPage)
    if OpenLastFileTips:
        Docu = open(FileLocation,"r",encoding='UTF-8')
        DocuName = Docu.name
        OpenMode = Docu.mode
        DocuFid = str(Docu.fileno)
        Docu = Docu.read()
        Editor.delete(1.0,tkinter.END)
        Editor.insert("end",Docu)
        TitlePage = DocuName + " - " + "轻量写作"
        MainWindow.title(TitlePage)
        PageInfo = 0
        PageInfoes = "打开方式：" + OpenMode + "     描述符：" + DocuFid
        PageInfo = tkinter.Label(MainWindow,text=PageInfoes)
        PageInfo.pack()
        os.remove("locatsave.ini")
except:
    pass

try:
    os.remove("locatsave.ini")
except:
    pass

MainWindow.mainloop()